<template>
	<view class="content">
		<text>{{voiceFre}}</text>
		<button @click="onStart">start</button>
		<button @click="onStop">stop</button>
		<button @click="onAubioStart">aubioTest</button>
	</view>
</template>

<script>
	import Recorder from 'recorder-core';
	import RecordApp from 'recorder-core/src/app-support/app';
	//所有平台必须引入的uni-app支持文件（如果编译出现路径错误，请把@换成 ../../ 这种）
	// import "../../node_modules/recorder-core/src/app-support/app-native-support.js"
	import "recorder-core/src/app-support/app-native-support.js"

	/** 需要编译成微信小程序时，引入微信小程序支持文件 **/
	// #ifdef MP-WEIXIN
	import 'recorder-core/src/app-support/app-miniProgram-wx-support.js'
	// #endif


	/** H5、小程序环境中：引入需要的格式编码器、可视化插件，App环境中在renderjs中引入 **/
	// #ifdef H5 || MP-WEIXIN
	//按需引入你需要的录音格式支持文件，如果需要多个格式支持，把这些格式的编码引擎js文件统统引入进来即可
	import 'recorder-core/src/engine/mp3'
	import 'recorder-core/src/engine/mp3-engine' //如果此格式有额外的编码引擎（*-engine.js）的话，必须要加上

	//可选的插件支持项
	import 'recorder-core/src/extensions/waveview'
	// #endif

	import FFT from 'fft-js';

	import aubio from 'aubiojs';
	// const aubio = require('aubiojs').default;
	// const {
	// 	AudioContext
	// } = require('node-web-audio-api');


	export default {
		data() {
			return {
				title: 'Hello',
				voiceFre: "",
				audioContext: null,
				analyser: null,
				intervalObj: null
			}
		},
		onLoad() {

		},
		mounted() {},
		methods: {
			onAubioStart() {
				this.AubioStart();
			},
			async AubioStart() {
				const sampleRate = 44100;
				// 创建 AudioContext
				const audioContext = new AudioContext({
					sampleRate: sampleRate
				});

				// 初始化 aubio.js
				const aubioModule = await aubio();

				// 创建音高检测器
				const bufferSize = 1024;
				const pitchDetector = new aubioModule.Pitch('yin', bufferSize, bufferSize, 44100);

				// 3. 启动麦克风
				let microphoneStream = await navigator.mediaDevices.getUserMedia({
					audio: true
				});

				// 4. 连接音频处理
				const source = audioContext.createMediaStreamSource(microphoneStream);
				const processor = audioContext.createScriptProcessor(bufferSize, 1, 1);

				source.connect(processor);
				processor.connect(audioContext.destination);

				// 5. 实时处理音频
				processor.onaudioprocess = (event) => {
					const inputBuffer = event.inputBuffer.getChannelData(0);
					const frequency = pitchDetector.do(inputBuffer);
					if(frequency>1000){
						return
					}
					// if(frequency<70||frequency>80){
					// 	return
					// }
					if (frequency > 0) {
						const notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
						const A4 = 440; // 基准频率 A4 = 440 Hz
						const halfSteps = Math.round(12 * Math.log2(frequency / A4));
						const octave = Math.floor(halfSteps / 12) + 4;
						const noteIndex = (halfSteps % 12 + 12) % 12;
						let voiceName = notes[noteIndex] + octave;

						console.log(`Detected pitch: ${frequency} Hz,` + voiceName);
						this.voiceFre=voiceName
					}
				};

			},
			onStart() {
				this.startMicrophone()
			},
			onStop() {
				clearInterval(this.intervalObj)
			},
			async startMicrophone() {
				try {
					const stream = await navigator.mediaDevices.getUserMedia({
						audio: true
					});
					this.startVoide(stream); // 处理音频流
				} catch (err) {
					console.error("无法访问麦克风:", err);
				}
			},

			startVoide(stream) {
				// 创建音频上下文
				this.audioContext = new(window.AudioContext || window.webkitAudioContext)();

				// 创建 AnalyserNode
				this.analyser = this.audioContext.createAnalyser();
				this.analyser.fftSize = 2048; // 设置FFT窗口大小

				// 将麦克风输入流连接到音频上下文
				const source = this.audioContext.createMediaStreamSource(stream);
				source.connect(this.analyser);

				this.intervalObj = setInterval(this.visualize, 100)
			},
			visualize() {
				// 获取频域数据（示例）
				const freqData = new Uint8Array(this.analyser.frequencyBinCount);
				this.analyser.getByteFrequencyData(freqData);
				console.log(freqData)

				// 获取时域数据（示例）
				const timeData = new Uint8Array(this.analyser.fftSize);
				this.analyser.getByteTimeDomainData(timeData);
				console.log(timeData)
				//   // 在此处绘制频谱或波形（使用 Canvas、WebGL 等）
				//   drawSpectrum(freqData);

				//   // 循环更新
				//   requestAnimationFrame(visualize);
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>